package functions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class CRSTlzw {
    
    public static Integer LZWcompressionValue(String original)//function that returns lzw value of compression
    {
    	int i=0;
    	int compressionSize=0;
    	
    	Map<String,Integer> dictionary = new HashMap<String,Integer>();
    	
    	String delims="[, ]+";                          //divide the string
    	String[] tokens = original.split(delims);        //in each array cell will be the line number
    	String[] elements = removeDuplicates(tokens);    //remove duplicate lines to construct our dictionary
 	  
    	for(i=0;i<elements.length;i++){
    		dictionary.put(elements[i],i);               //add to dictionary all the lines in the string
    	}
    	   	
    	String w = "";                                   //compress with LZW algorithm
    	List<Integer> result = new ArrayList<Integer>();
        for (String c : tokens) {
        	String wc = w + c;
            if (dictionary.containsKey(wc))
                w = wc;
            else {
                result.add(dictionary.get(w));
                dictionary.put(wc, i++);
                w = "" + c;
            }
        }
        
 
        // Output the code for w.
        if (!w.equals(""))
            result.add(dictionary.get(w));
        
        compressionSize=result.size();            //get the compression result size
        return compressionSize;
    	

    }
    
    public static String[] removeDuplicates(String[] arr) {
    	  return new HashSet<String>(Arrays.asList(arr)).toArray(new String[0]);
    	}
}




